#include <string>
#include <iostream>
#include <sstream>

#include "ConnectionHandlerMixnode.hpp"
#include "Logger.hpp"
#include "ConnectSocket.hpp"
#include "SMIMEMessage.hpp"
#include <sys/socket.h>


ConnectionHandlerMixnode::ConnectionHandlerMixnode(const std::string &CACert, const std::string &MyCert, const std::string &MyKey) : ConnectionHandler(), CACert(CACert), MyCert(MyCert), MyKey(MyKey) {
}

void ConnectionHandlerMixnode::handle() {
	std::stringstream stream;
	
	char buffer[1024];
	int length;
	do {
		length = recv(connection->getFD(), buffer, 1024, 0);
		stream.write(buffer, length);
	} while (length != 0);

	std::string content = stream.str();
	int lineEnd = content.find('\n');
	if (content[lineEnd - 1] == '\r') {
		lineEnd--;
	}
	std::string firstLine = content.substr(0, lineEnd);

	SMIMEMessage* message = new SMIMEMessage(content);
	message->Decrypt(MyCert, MyKey);

	//if we should forward the message
	if (firstLine.find("To: ") == 0) {
		std::string to = firstLine.substr(4, lineEnd - 4);
		std::cout << "forwarding to " << to << std::endl;

		//forward it
		ConnectSocket* socket = new ConnectSocket(to, 4433);
		TCPConnection connection = socket->connect();

		std::stringstream readStream(message->GetDecryptedMessage());
		char buffer[1024];
		int length = 0;
		do {
			readStream.read(buffer, 1024);
			length = readStream.gcount();
			send(connection.getFD(), &buffer, sizeof(char) * length, 0);
		} while (length != 0);
		connection.close();
		
		//if we are the recipient
	} else {
		SMIMEMessage* message2 = new SMIMEMessage(message->GetDecryptedMessage());
		//verify signature and print the message
		if (message2->VerifySignature(CACert)) {
			std::cout << "Message from " << message2->GetSigningParty() << ":" << std::endl;
			std::cout << message2->GetSignedMessage() << std::endl;
			std::cout << "-------------------" << std::endl;
		}
	}
}

ConnectionHandlerMixnode::~ConnectionHandlerMixnode() {
}

